<?php namespace Home\Controller; 
use Hdphp\Controller\Controller;
class CateGoryController extends Controller{
	public function index(){
		$cid=Q('get.cid',0,'intval');
		//获取顶级分类
		$cateGory= new \Common\Model\CateGory;
		$cateGoryData=$cateGory->where("pid=0")->get();
		$cGoryData=$cateGory->where("pid=0 and cid=$cid")->pluck('cname');
//		p($cGoryData);
		View::with('cGoryData',$cGoryData);
//		p($cateGoryData);exit;
		View::with('cateGoryData',$cateGoryData);
		
		//通过当前分类的cid获得所有子级的cid
		
		$cids=$cateGory->getSon($cateGory->get(),$cid);
		$cids[]=$cid;
//		p($cids);exit;
		
		//根据cid获得商品的gid
		$goods=new \Common\Model\Goods;
		$gids=$goods->where("category_cid IN(" . implode('|',$cids) . ")")->lists('gid');
		
		
		
		if($gids){
			$gids=implode(',', $gids);
			//通过gid到商品属性表里查找属性
			$goodsAttr=new \Common\Model\GoodsAttr;
			$goodsAttrData=$goodsAttr->where("goods_gid IN ($gids)")->groupBy('gtvalue')->get();
//			p($goodsAttrData);exit;

			//把相同的taid属性放在一起
			$sameTaid=[];
			foreach($goodsAttrData as $v){
				$sameTaid[$v['typeattr_taid']][]=$v;
			}
//			p($sameTaid);exit;
			//组合名字和值
			$xinAttr=[];
			$typeAttr= new \Common\Model\TypeAttr;
			foreach($sameTaid as $typeattr_taid=>$v){
				$xinAttr[]=[
					'name'=>$typeAttr->where("taid={$typeattr_taid}")->pluck('taname'),
					'value'=>$v
				];
			}
//			p($xinAttr);exit;
			View::with('xinAttr',$xinAttr);	
			//筛选效果***************************
			//地址栏效果 0_0_0_......
			$num=count($xinAttr);
//			p($num);exit;
			$param=isset($_GET['param']) ? explode('_',$_GET['param']) : array_fill(0,$num,0);
//			p($param);exit;
			View::with("param",$param);
			//筛选操作，获得商品gid
			$finalGids=$this->filter($param,$gids);
//			p($finalGids);
			
		}else{
			View::with('xinAttr',[]);
		}
		View::make();
	}

	private function filter($param,$cidGids){
		$goodsAttr=new \Common\Model\GoodsAttr;
		$gidArr=[];
		foreach($param as $gtid){
			//如果点击的不是“全部”的时候 根据gtid找到商品的gid
			if($gtid){
				//查询到商品属性的名称
				$gtvalue=$goodsAttr->where("gtid={$gtid}")->pluck('gtvalue');
//				p($gtvalue);exit;
				//通过名称查询到goods_gid
				$gidArr[]=$goodsAttr->where(['gtvalue'=>$gtvalue])->lists('goods_gid');
			}
		}
//		p($gidArr);exit;
		//如果用户不是全部“全部”的时候
		if($gidArr){
			$goods_gid=$gidArr[0];
			foreach($gidArr as $v){
//				p($v);exit;
				$goods_gid=array_intersect($v,$goods_gid);
			}
//			p($cidGids);exit;
			$cidGids=explode(',', $cidGids);
			//$goods_gid有可能是其它分类的gid 确保是当前分类 再取交集
			$finalGids=array_intersect($goods_gid,$cidGids);
		}else{
			//如果全部是“全部”的时候
			$finalGids=$cidGids;
		}
		return $finalGids;
	}
}
